package com.zimmur.app.mocolink.manage.web.vogData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.zimmur.app.mocolink.domain.util.DateUtils;
import com.zimmur.app.mocolink.domain.util.MD5;
import com.zimmur.app.mocolink.domain.util.StringUtils;
import com.zimmur.app.mocolink.manage.web.common.PropertiesCommon;
import com.zimmur.app.mocolink.manage.web.util.HttpClientUtil;

public class VogDataRequestUtil {
	private static final Logger log = LoggerFactory.getLogger(VogDataRequestUtil.class);
	private static String basePath;
	private static String appkey;
	private static String token;
	
	static{
		basePath=PropertiesCommon.getProperty("vogApi.basePath");
		appkey=PropertiesCommon.getProperty("vogApi.appkey");
		token=PropertiesCommon.getProperty("vogApi.token");
	}
	public static String getRequest(List<NameValuePair> params,String api){
		try {
			long time = System.currentTimeMillis();
			String sign =getSign(params, time, time);
			String url = basePath+api;
			List<NameValuePair> headers=new ArrayList<>();
			headers.add(new BasicNameValuePair("appkey",appkey));
			headers.add(new BasicNameValuePair("nonce",time+""));
			headers.add(new BasicNameValuePair("signature",sign));
			headers.add(new BasicNameValuePair("timestamp",time+""));
			String result = HttpClientUtil.doGet(url, params, headers);
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}
	
	public static JSONObject postRequest(){
		return null;
	}
	
	private static String getSign(List<NameValuePair> params,long timestamp,long nonce){
        ArrayList<String> list = new ArrayList<String>();
        for(NameValuePair pair:params){
            if(!StringUtils.isBlank(pair.getValue())){
                list.add(pair.getName()+pair.getValue());
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        //Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String paramStr=sb.toString();
        //System.out.println(paramStr);
        String result =timestamp+""+nonce+appkey+token+paramStr;
        //System.out.println(result);
        result = sortString(result);
        //System.out.println(result);
        String sign =MD5.MD5Encode(result).toUpperCase();
        return sign;
    }
	
	private static String sortString(String sign){
		char[] charArray=sign.toCharArray();
		Arrays.sort(charArray);
		return new String(charArray);
	}
}
